package com.tanhua.server.service;

import com.tanhua.autoconfig.templates.OssTemplate;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Voice;
import com.tanhua.domain.mongo.VoicePass;
import com.tanhua.domain.vo.VoiceVo;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.VoiceApi;
import com.tanhua.dubbo.api.mongo.VoicePassApi;
import com.tanhua.server.exceptions.TanhuaException;
import com.tanhua.server.interceptors.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class SoundService {


    @Autowired
    private OssTemplate ossTemplate;


    @Autowired
    private RedisTemplate redisTemplate;


    @DubboReference
    private VoiceApi voiceApi;
    @DubboReference
    private UserInfoApi userInfoApi;

    public ResponseEntity sendSound(MultipartFile soundFile) throws IOException {
        //将语音以流的方式存到阿里云中
        String soundUrl = ossTemplate.upload(soundFile.getOriginalFilename(), soundFile.getInputStream());

        Voice voice = new Voice();
        voice.setId(new ObjectId());
        voice.setUserId(UserHolder.getUserId());
        voice.setSoundUrl(soundUrl);
        UserInfo userInfo = userInfoApi.findById(UserHolder.getUserId());
        voice.setGender(userInfo.getGender());
        voiceApi.save(voice);

        return ResponseEntity.ok(null);
    }

    @DubboReference
    private VoicePassApi voicePassApi;

    //接收语音
    public ResponseEntity getSound() {

        UserInfo userInfo = userInfoApi.findById(UserHolder.getUserId());
        String gender = userInfo.getGender();

        //获取除自己外，异性的语音集合
        List<Voice> voiceList = voiceApi.getSound(UserHolder.getUserId(), gender);

        //查询已经获取过得异性合集
        List<VoicePass> voicePassList=voicePassApi.findList(UserHolder.getUserId());
        ArrayList<ObjectId> arrayList = new ArrayList();
        //将获取到的语音id填充到集合中
            for (VoicePass voicePass : voicePassList) {
                ObjectId objectId = new ObjectId(voicePass.getPassId());
                arrayList.add(objectId);
            }
         //随机获取一条语音
        int randomNum = new Random().nextInt(voiceList.size());
        Voice voice = voiceList.get(randomNum);

        //判断该语音是否获取过
        while (true) {
            if (!arrayList.contains(voice.getId())) {
                break;
            }
            randomNum = new Random().nextInt(voiceList.size());
            voice = voiceList.get(randomNum);
        }

        VoiceVo voiceVo = new VoiceVo();
        UserInfo userInfo1 = userInfoApi.findById(voice.getUserId());
        BeanUtils.copyProperties(userInfo1, voiceVo);

        voiceVo.setId(Integer.parseInt(voice.getUserId().toString()));

        voiceVo.setSoundUrl(voice.getSoundUrl());

        //将本日获取语音次数存到缓存中
        if (!redisTemplate.hasKey("voice_getSound_" + UserHolder.getUserId())) {

            redisTemplate.boundValueOps("voice_getSound_" + UserHolder.getUserId()).set(2, 1, TimeUnit.DAYS);
            voiceVo.setRemainingTimes(2);

            VoicePass voicePass = new VoicePass();
            voicePass.setId(new ObjectId());
            voicePass.setUserId(UserHolder.getUserId());
            voicePass.setPassId(voice.getId().toString());
            voicePass.setPublishUserId(voice.getUserId());
            voicePass.setCreated(new Date().getTime());
            voicePassApi.save(voicePass);

            return ResponseEntity.ok(voiceVo);
        }
        //根据缓存的次数判断是否还可以继续获取语音
        Integer number = (Integer) redisTemplate.boundValueOps("voice_getSound_" + UserHolder.getUserId()).get();

        if (number == 0) {
            throw new TanhuaException(500, "今日次数已用完，请明天再来！");
        }

        voiceVo.setRemainingTimes(number - 1);
        redisTemplate.boundValueOps("voice_getSound_" + UserHolder.getUserId()).set(number - 1, 1, TimeUnit.DAYS);


        VoicePass voicePass = new VoicePass();
        voicePass.setId(new ObjectId());
        voicePass.setUserId(UserHolder.getUserId());
        voicePass.setPassId(voice.getId().toString());
        voicePass.setPublishUserId(voice.getUserId());
        voicePass.setCreated(new Date().getTime());
        voicePassApi.save(voicePass);



        return ResponseEntity.ok(voiceVo);
    }
}
